import 'dart:async';

import 'package:distribution_mall_flutter/entity/user/user_info_entity.dart';
import 'package:distribution_mall_flutter/http/modules/user.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class UserInfoState {
  UserDisplayEntity? userInfo;

  UserInfoState({this.userInfo});

  UserInfoState.initial();
  UserInfoState copyWith({UserDisplayEntity? userInfo}) => UserInfoState(
        userInfo: userInfo ?? this.userInfo,
      );
}

final userInfoProvider =
    StateNotifierProvider.autoDispose<UserInfoViewModel, UserInfoState>((ref) {
  return UserInfoViewModel();
});

class UserInfoViewModel extends StateNotifier<UserInfoState> {
  UserInfoViewModel() : super(UserInfoState.initial());

  Future<UserDisplayEntity?> getUserInfo() async {
    if (!EPstorage.isLogin()) return null;
    UserDisplayEntity? data = await UserApi.getDisplay({});
    if (data == null) return null;
    state = state.copyWith(userInfo: data);
    EPstorage.userInfo.put(UserInfoBoxKey.nick, data.nickName);
    EPstorage.userInfo.put(UserInfoBoxKey.id, data.userId);
    EPstorage.userInfo.put(UserInfoBoxKey.avatarUrl, data.avatarUrl);
    EPstorage.userInfo.put(UserInfoBoxKey.username, data.username);
    return data;
  }
}
